<?php

namespace app\admin\service;


use app\admin\model\AuthGroupAccess;
use app\admin\validate\Admin;
use think\exception\ValidateException;
use app\traits\Result;
use app\admin\model\Admin as AdminModel;
use think\facade\Config;
use think\helper\Str;
use think\crypt\Crypt;

class AdminService
{
    use Result;

    /**
     * 添加/编辑管理员
     * @param $data
     * @param string $scene
     * @return array|string
     */
    public static function storeAdmin($data,$scene='add'){
        $data['state'] = isset( $data['state'])? $data['state']:0;
        try {
            //如果没有密码修改
            if (isset($data['password'])&&empty($data['password'])){
                $scene = 'no_change';
            }
            validate(Admin::class)->scene($scene)->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            $msg =Result::error($e->getError(),null, ['token'=>request()->buildToken()]);
            return $msg;
        }


        $model = new AdminModel();
        if ($scene !='add') {
            //如果没有密码修改
            if (isset($data['password'])&&!empty($data['password'])){
                $data['password'] = md5($data['password'].$data['token']);
            }else{
                unset($data['password']);
            }
            unset($data['token']);
            $result = $model->exists(true)->update($data);

            //用户角色关联
            self::adminToRole($data['id'],$data['group_id']);
            if ($result) {
                return Result::success('编辑成功');
            } else {
                return Result::error('编辑失败');
            }
        } else {
            $data['token'] = Str::random(10);
            $data['password'] = md5($data['password'].$data['token']);
            $data['last_login'] = date('Y-m-d H:m:s');
            $result = $model->save($data);

            //用户角色关联
            self::adminToRole($model->id,$data['group_id']);
            if ($result) {
                return Result::success('添加成功');
            } else {
                return Result::error('添加失败');
            }
        }
    }

    /**
     * 管理员关联角色
     * @param $uids
     */
    public static function adminToRole($uid,$group_id){
        $group_id = explode(',', $group_id);

        //删除之前的用户角色关系
        AuthGroupAccess::where('uid',$uid)->delete();
        $list = [];
        foreach ($group_id as $item){
            $list[] = ['uid'=>$uid,'group_id'=>$item];
        }
        $model = new AuthGroupAccess();
        $model->saveAll($list);
    }

    /**
     * 登录后台
     * @param $data
     * @return array|string
     */
    public static function login($data){
        try {
            validate(Admin::class)->scene('login')->check($data);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            $msg =Result::error($e->getError(),null, ['token'=>request()->buildToken()]);
            return $msg;
        }

        //获取登录admin信息
        self::autoSession($data['username']);
        //记住密码
        if(isset($data['remember']) && $data['remember']=='on'){
            $member['username'] = $data['username'];
            $member['password'] = $data['password'];
            $member['remember'] = $data['remember'];
            $remember = Crypt::encrypt(serialize($member),Config::get('login_admin.crypt'));
            cookie('remember', $remember);//记住我
        }else{
            cookie('remember', null);
        }

        return Result::success('登录成功');
    }

    /**
     * 登录session保存
     * @param $username
     */
    public static  function autoSession($username){
        $admin = AdminModel::where('username|email',$username)->withoutField('password,token')->find();
        $admin->login_ip =  request()->ip();
        $admin->last_login = date('Y-m-d H:m:s');
        $admin->save();

        //获取admin对象数据-保存session
        $auth = Config::get('login_admin.auth_uid');
        session($auth,$admin->id);
    }

    /**
     * 获取登录用户信息
     * @param $name
     * @return mixed
     */
    public static  function getLoginInfo($name=false){
        $auth = Config::get('login_admin.auth_uid');
        $uid = session($auth);

        $admin = AdminModel::withoutField('password,token')->find($uid)->getData();
        if ($name){
            return $admin[$name];
        }else{
            return $admin;
        }
    }

    /**
     * 退出登录
     */
    public static function logout(){
        $auth = Config::get('login_admin.auth_uid');
        session($auth,null);
        session(null);
    }

}